package com.sg.service.biz.app.nb;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sg.common.util.CommonFunctionHelper;
import com.sg.common.util.RedisUtil;
import com.sg.dto.biz.app.req.*;
import com.sg.dto.biz.app.res.*;
import com.sg.dto.integration.component.CurrentCycleDto;
import com.wicket.okrapp.common.baseinfo.BaseInfoDO;
import com.wicket.okrapp.common.util.DateTimeUtil;
import com.wicket.okrcomponent.common.exception.BizException;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.skywalking.apm.toolkit.trace.Tag;
import org.apache.skywalking.apm.toolkit.trace.Tags;
import org.apache.skywalking.apm.toolkit.trace.Trace;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.*;

/**
 * @author ： 手工接入方法
 * @version 1.0
 * @since 2022/5/28 15:32
 */
@Service
public class NbInterfaceMode {
    @Resource
    private RedisUtil redisUtil;

    @Resource
    private DataSource dataSource;

    /**
     * code:receptionService
     * name:M3判断进入房间，出参步骤与检查项值
     * desc:undefined
     * gen by moon at 9/21/2022, 12:43:21 AM
     **/
    @Trace(operationName = "M3判断进入房间，出参步骤与检查项值")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public ImplementBizConstructAccessParameterFieldRespDto implementBizConstructAccessParameterField(ImplementBizConstructAccessParameterFieldReqDto reqDto) {
        return BeanUtil.toBean(reqDto, ImplementBizConstructAccessParameterFieldRespDto.class);
    }

    /**
     * code:getNextCycle
     * name:M3获取当前及下一个周期（特殊方法）
     * desc:undefined
     * gen by moon at 11/3/2022, 12:06:10 AM
     **/
    @Trace(operationName = "M3获取当前及下一个周期（特殊方法）")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public ObtainGetCurrentAndNextCycleRespDto obtainGetCurrentAndNextCycle(ObtainGetCurrentAndNextCycleReqDto reqDto) {
        ObtainGetCurrentAndNextCycleRespDto retData = new ObtainGetCurrentAndNextCycleRespDto();
        CurrentCycleDto current = null;
        long count = 0;
        for (CurrentCycleDto one : reqDto.getCurrentCycleList()) {
            if (one.getCycleStartTime().compareTo(reqDto.getCompareTime()) <= 0 && one.getCycleEndTime().compareTo(reqDto.getCompareTime()) >= 0) {
                current = one;
                break;
            }
            count++;
        }
        if (ObjectUtils.isEmpty(current)) {
            return retData;
        }
        retData.setCurrentCycleId(current.getCycleId());

        CurrentCycleDto last = null;
        CurrentCycleDto next = null;
        Long lastIndex = count - 1;
        Long nextIndex = count + 1;
        if (lastIndex >= 0) {
            last = reqDto.getCurrentCycleList().get(lastIndex.intValue());
        }

        if (nextIndex < reqDto.getCurrentCycleList().size()) {
            next = reqDto.getCurrentCycleList().get(nextIndex.intValue());
        }

        if (ObjectUtils.isNotEmpty(last)) {
            if (last.getCycleStartTime().compareTo(current.getCycleEndTime()) > 0) {
                retData.setNextCycleId(last.getCycleId());
                return retData;
            }
        }

        if (ObjectUtils.isNotEmpty(next)) {
            if (next.getCycleStartTime().compareTo(current.getCycleEndTime()) > 0) {
                retData.setNextCycleId(next.getCycleId());
                return retData;
            }
        }

        return retData;
    }

    /**
     * code:getLastAndNextCycle
     * name:M3获取当前及上一个下一个周期
     * desc:undefined
     * gen by moon at 11/7/2022, 4:32:10 AM
     **/
    @Trace(operationName = "M3获取当前及上一个下一个周期")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public ObtainGetCurrentAndLastAndNextCycleRespDto obtainGetCurrentAndLastAndNextCycle(ObtainGetCurrentAndLastAndNextCycleReqDto reqDto) {
        ObtainGetCurrentAndLastAndNextCycleRespDto retData = new ObtainGetCurrentAndLastAndNextCycleRespDto();
        CurrentCycleDto current = null;
        long count = 0;
        for (CurrentCycleDto one : reqDto.getCurrentCycleList()) {
            if (one.getCycleStartTime().compareTo(reqDto.getCompareTime()) <= 0 && one.getCycleEndTime().compareTo(reqDto.getCompareTime()) >= 0) {
                current = one;
                break;
            }
            count++;
        }
        if (ObjectUtils.isEmpty(current)) {
            return retData;
        }
        retData.setCurrentCycleId(current.getCycleId());

        CurrentCycleDto last = null;
        CurrentCycleDto next = null;
        Long lastIndex = count - 1;
        Long nextIndex = count + 1;
        if (lastIndex >= 0) {
            last = reqDto.getCurrentCycleList().get(lastIndex.intValue());
        }

        if (nextIndex < reqDto.getCurrentCycleList().size()) {
            next = reqDto.getCurrentCycleList().get(nextIndex.intValue());
        }

        if (ObjectUtils.isNotEmpty(last)) {
            if (last.getCycleStartTime().compareTo(current.getCycleEndTime()) > 0) {
                retData.setNextCycleId(last.getCycleId());
            } else if (last.getCycleEndTime().compareTo(current.getCycleStartTime()) < 0) {
                retData.setLastCycleId(last.getCycleId());
            }
        }

        if (ObjectUtils.isNotEmpty(next)) {
            if (next.getCycleStartTime().compareTo(current.getCycleEndTime()) > 0) {
                retData.setNextCycleId(next.getCycleId());
            } else if (next.getCycleEndTime().compareTo(current.getCycleStartTime()) < 0) {
                retData.setLastCycleId(last.getCycleId());
            }
        }

        return retData;
    }

    /**
     * code:getPublicFieldCache
     * name:M2-获取内存中业务字段（特殊方法）
     * desc:undefined
     * gen by moon at 12/3/2022, 7:43:19 PM
     **/
    @Trace(operationName = "M2-获取内存中业务字段（特殊方法）")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public ObtainGetPublicFieldCacheRespDto obtainGetPublicFieldCache(ObtainGetPublicFieldCacheReqDto reqDto) {
        // TODO ruizhe skai dong ; 12/3/2022, 7:43:19 PM
        return new ObtainGetPublicFieldCacheRespDto();
    }

    /**
     * code:findAllLevelCodeList
     * name:M-公共查询找祖先列表（特殊方法）
     * desc:undefined
     * gen by moon at 2/5/2023, 10:48:45 PM
     **/
    @Trace(operationName = "M-公共查询找祖先列表（特殊方法）")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public QueryLookAncestorNodeListRespDto queryLookAncestorNodeList(QueryLookAncestorNodeListReqDto reqDto) {
        QueryLookAncestorNodeListRespDto retData = new QueryLookAncestorNodeListRespDto();
        String oriCode = null;
        if (reqDto.getEvaObjTargetCycleCode() != null && !reqDto.getEvaObjTargetCycleCode().isEmpty()) {
            oriCode = reqDto.getEvaObjTargetCycleCode();
        }

        if (reqDto.getAssistNodeTypeObjectCode() != null && !reqDto.getAssistNodeTypeObjectCode().isEmpty()) {
            oriCode = reqDto.getAssistNodeTypeObjectCode();
        }

        if (reqDto.getComCode() != null && !reqDto.getComCode().isEmpty()) {
            oriCode = reqDto.getComCode();
        }

        if (oriCode == null || oriCode.isEmpty()) {
            return retData;
        }
        int dealSize = 4;
        while (oriCode.length() >= dealSize) {
            String oneCode = oriCode.substring(0, dealSize);
            if (oneCode != null && !oneCode.isEmpty()) {
                EvaObjTargetCycleDto elm = new EvaObjTargetCycleDto();
                elm.setEvaObjTargetCycleCode(oneCode);
                retData.getEvaObjTargetCycleList().add(elm);
                retData.getLookAncestorNodeList().add(oneCode);
            }
            dealSize = dealSize + 4;
        }
        retData.getLookAncestorNodeList().remove(oriCode);
        return retData;

    }

    /**
     * code:distributedUnlocking
     * name:M3分布式解锁
     * desc:undefined
     * gen by moon at 6/26/2023, 10:08:30 PM
     **/
    @Trace(operationName = "M3分布式解锁")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public ImplementDistributedUnlockingRespDto implementDistributedUnlocking(ImplementDistributedUnlockingReqDto reqDto) {
        ImplementDistributedUnlockingRespDto retData = new ImplementDistributedUnlockingRespDto();
        redisUtil.releaseLock(reqDto.getCommPrimaryKey(), reqDto.getCommPrimaryKey());
        return retData;
    }

    /**
     * code:distributedLocking
     * name:M3-分布式加锁
     * desc:undefined
     * gen by moon at 6/26/2023, 10:09:39 PM
     **/
    @Trace(operationName = "M3-分布式加锁")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public ImplementDistributedLockingRespDto implementDistributedLocking(ImplementDistributedLockingReqDto reqDto) {
        ImplementDistributedLockingRespDto retData = new ImplementDistributedLockingRespDto();
        boolean bRet = redisUtil.getLock(reqDto.getCommPrimaryKey(), reqDto.getCommPrimaryKey(), reqDto.getDuration());
        retData.setTureOrFalse("TRUE");
        if (!bRet) {
            retData.setTureOrFalse("FALSE");
        } else {
            if (!CommonFunctionHelper.checkBaseInfo()) {
                CommonFunctionHelper.setBaseInfoToLocal(new BaseInfoDO());
            }
            CommonFunctionHelper.getBaseInfoFromLocal().getLockList().add(reqDto.getCommPrimaryKey());
        }
        return retData;
    }

    /**
     * code:distributedWaitLocking
     * name:M3新增分布式加等待锁
     * desc:undefined
     * gen by moon at 7/5/2023, 10:41:16 PM
     **/
    @Trace(operationName = "M3新增分布式加等待锁")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public AddDistributedWaitLockingRespDto addDistributedWaitLocking(AddDistributedWaitLockingReqDto reqDto) {
        AddDistributedWaitLockingRespDto retData = new AddDistributedWaitLockingRespDto();
        retData.setTureOrFalse("FALSE");
        Long count = 0L;
        while (true) {
            count++;
            if (count >= 1800) {
                break;
            }
            boolean bret = redisUtil.getLock(reqDto.getCommPrimaryKey(), reqDto.getCommPrimaryKey(), reqDto.getDuration());
            if (bret) {
                retData.setTureOrFalse("TRUE");
                break;
            }
            try {
                Thread.sleep(1000);
            } catch (Exception e) {

            }
        }
        return retData;
    }

    /**
     * code:distributedLocking
     * name:M3加分布式主题锁（特殊方法）
     * desc:undefined
     * gen by moon at 9/30/2023, 6:18:19 PM
     **/
    @Trace(operationName = "M3加分布式主题锁（特殊方法）")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public ImplementDistributedMotifLockingRespDto implementDistributedMotifLocking(ImplementDistributedMotifLockingReqDto reqDto) {
        ImplementDistributedMotifLockingRespDto retData = new ImplementDistributedMotifLockingRespDto();
        String key = null;
        if (reqDto.getCommPrimaryKey() != null) {
            key = reqDto.getCommPrimaryKey();
        } else {
            key = reqDto.getCommPrimaryKey();
        }


        if (reqDto.getRedisDataObjectCatalogue() != null) {
            key = reqDto.getRedisDataObjectCatalogue() + ":" + key;
        }
        boolean bRet = redisUtil.getLock(key, key, reqDto.getDuration());
        retData.setTureOrFalse("TRUE");
        if (!bRet) {
            retData.setTureOrFalse("FALSE");
        } else {
            if (!CommonFunctionHelper.checkBaseInfo()) {
                CommonFunctionHelper.setBaseInfoToLocal(new BaseInfoDO());
            }
            CommonFunctionHelper.getBaseInfoFromLocal().getLockList().add(key);
            if (reqDto.getDistributedLockMotif() != null) {
                if (!CommonFunctionHelper.getBaseInfoFromLocal().getThemeLockIndex().containsKey(reqDto.getDistributedLockMotif())) {
                    CommonFunctionHelper.getBaseInfoFromLocal().getThemeLockIndex().put(reqDto.getDistributedLockMotif(), new ArrayList<>());
                }
                CommonFunctionHelper.getBaseInfoFromLocal().getThemeLockIndex().get(reqDto.getDistributedLockMotif()).add(key);
            }
        }
        return retData;
    }

    /**
     * code:distributedUnlocking
     * name:M3批量解分布式主题锁（特殊方法）
     * desc:undefined
     * gen by moon at 9/30/2023, 6:18:21 PM
     **/
    @Trace(operationName = "M3批量解分布式主题锁（特殊方法）")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public ImplementDistributedMotifUnlockingRespDto implementDistributedMotifUnlocking(ImplementDistributedMotifUnlockingReqDto reqDto) {
        ImplementDistributedMotifUnlockingRespDto retData = new ImplementDistributedMotifUnlockingRespDto();
        if (!CommonFunctionHelper.checkBaseInfo()) {
            CommonFunctionHelper.setBaseInfoToLocal(new BaseInfoDO());
        }
        if (CommonFunctionHelper.getBaseInfoFromLocal().getThemeLockIndex().containsKey(reqDto.getDistributedLockMotif())) {
            if (CollectionUtil.isNotEmpty(CommonFunctionHelper.getBaseInfoFromLocal().getThemeLockIndex().get(reqDto.getDistributedLockMotif()))) {
                for (String oneLockKey : CommonFunctionHelper.getBaseInfoFromLocal().getThemeLockIndex().get(reqDto.getDistributedLockMotif())) {
                    redisUtil.releaseLock(oneLockKey, oneLockKey);
                }
            }
        }
        return retData;
    }

    /**
     * code:probeDistributedLock
     * name:M3探测分布式锁（特殊方法）
     * desc:undefined
     * gen by moon at 9/30/2023, 6:18:24 PM
     **/
    @Trace(operationName = "M3探测分布式锁（特殊方法）")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public ImplementProbeDistributedLockRespDto implementProbeDistributedLock(ImplementProbeDistributedLockReqDto reqDto) {
        ImplementProbeDistributedLockRespDto retData = new ImplementProbeDistributedLockRespDto();
        if (redisUtil.isLockExist(reqDto.getCommPrimaryKey())) {
            retData.setTureOrFalse("TRUE");
        } else {
            retData.setTureOrFalse("FALSE");
        }
        return retData;
    }

    /**
     * code:distributedLocking
     * name:M3执行防并发行为主题锁（特殊方法）
     * desc:undefined
     * gen by moon at 1/15/2024, 3:00:19 AM
     **/
    @Trace(operationName = "M3执行防并发行为主题锁（特殊方法）")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public ImplementConcurrentBehaviorThemeLockRespDto implementConcurrentBehaviorThemeLock(ImplementConcurrentBehaviorThemeLockReqDto reqDto) {
        String lockKeyPrefix = reqDto.getBehaviorThemeLockCode() + "_" + reqDto.getCommPrimaryKey();
        if (reqDto.getCustomField1() != null) {
            lockKeyPrefix = lockKeyPrefix + "_" + reqDto.getCustomField1();
        }

        if (reqDto.getCustomField2() != null) {
            lockKeyPrefix = lockKeyPrefix + "_" + reqDto.getCustomField2();
        }

        if (reqDto.getCustomField3() != null) {
            lockKeyPrefix = lockKeyPrefix + "_" + reqDto.getCustomField3();
        }


        if (reqDto.getRedisDataObjectCatalogue() != null) {
            lockKeyPrefix = reqDto.getRedisDataObjectCatalogue() + ":" + lockKeyPrefix;
        }
        Long duration = 0L;
        duration = DateTimeUtil.getSecond(reqDto.getTimeUnitType(), reqDto.getDuration());
        ImplementConcurrentBehaviorThemeLockRespDto retData = new ImplementConcurrentBehaviorThemeLockRespDto();
        boolean bRet = redisUtil.getLock(lockKeyPrefix, lockKeyPrefix, duration);
        retData.setPreventConcurrentLockingSituations("EMPTY_LOCK_SUCCESSFUL");
        if (!bRet) {
            retData.setPreventConcurrentLockingSituations("CONCURRENT_LOCK_FAILURE");
        } else {
            if (!CommonFunctionHelper.checkBaseInfo()) {
                CommonFunctionHelper.setBaseInfoToLocal(new BaseInfoDO());
            }
            CommonFunctionHelper.getBaseInfoFromLocal().getLockList().add(lockKeyPrefix);
        }
        return retData;
    }

    /**
     * code:distributedBatchUnlock
     * name:M3批量解锁并发行为主题锁（特殊方法）
     * desc:undefined
     * gen by moon at 1/15/2024, 3:00:25 AM
     **/
    @Trace(operationName = "M3批量解锁并发行为主题锁（特殊方法）")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public BatchUpdateUnlockingConcurrentBehaviorThemesRespDto batchUpdateUnlockingConcurrentBehaviorThemes(BatchUpdateUnlockingConcurrentBehaviorThemesReqDto reqDto) {
        String lockKeyPrefix = reqDto.getBehaviorThemeLockCode();
        if (reqDto.getCommPrimaryKey() != null) {
            lockKeyPrefix = lockKeyPrefix + "_" + reqDto.getCommPrimaryKey();
        }
        if (reqDto.getCustomField1() != null) {
            lockKeyPrefix = lockKeyPrefix + "_" + reqDto.getCustomField1();
        }

        if (reqDto.getCustomField2() != null) {
            lockKeyPrefix = lockKeyPrefix + "_" + reqDto.getCustomField2();
        }

        BatchUpdateUnlockingConcurrentBehaviorThemesRespDto retData = new BatchUpdateUnlockingConcurrentBehaviorThemesRespDto();
        List<String> lockList = redisUtil.findKeysByPrefix(lockKeyPrefix);
        for (String one : lockList) {
            redisUtil.releaseLock(one, one);
        }
        return retData;
    }

    public static void main(String[] args) {
        NbInterfaceMode o = new NbInterfaceMode();
        ImplementGeneralSubsectionQueryBusinessDataReqDto req = new ImplementGeneralSubsectionQueryBusinessDataReqDto();
        req.setDatasNum(100l);
        req.setOrderRule("FROM_LARGE_TO_SMALL");
        req.setOrderFieldName("name");
        req.setBusinessDataSetTableName("oms_index");
        req.setRefCustomField1("phone");
        req.setRefCustomFieldValue1("18598989988");
        ImplementGeneralSubsectionQueryBusinessDataRespDto ret = o.implementGeneralSubsectionQueryBusinessData(req);
        System.out.println(ret);
    }

    /**
     * code:distributedUnlocking
     * name:M3执行解锁并发行为主题锁（特殊方法）
     * desc:undefined
     * gen by moon at 1/15/2024, 3:00:32 AM
     **/
    @Trace(operationName = "M3执行解锁并发行为主题锁（特殊方法）")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public ImplementUnlockingConcurrentBehaviorThemesRespDto implementUnlockingConcurrentBehaviorThemes(ImplementUnlockingConcurrentBehaviorThemesReqDto reqDto) {
        String lockKeyPrefix = reqDto.getBehaviorThemeLockCode() + "_" + reqDto.getCommPrimaryKey();
        if (reqDto.getCustomField1() != null) {
            lockKeyPrefix = lockKeyPrefix + "_" + reqDto.getCustomField1();
        }

        if (reqDto.getCustomField2() != null) {
            lockKeyPrefix = lockKeyPrefix + "_" + reqDto.getCustomField2();
        }

        if (reqDto.getCustomField3() != null) {
            lockKeyPrefix = lockKeyPrefix + "_" + reqDto.getCustomField3();
        }

        ImplementUnlockingConcurrentBehaviorThemesRespDto retData = new ImplementUnlockingConcurrentBehaviorThemesRespDto();
        redisUtil.releaseLock(lockKeyPrefix, lockKeyPrefix);
        return retData;
    }

    /**
     * code:addMemoryBusinessData
     * name:M3新增内存业务数据（特殊方法）
     * desc:undefined
     * gen by moon at 3/15/2024, 11:35:19 PM
     **/
    @Trace(operationName = "M3新增内存业务数据（特殊方法）")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public AddMemoryBusinessDataRespDto addMemoryBusinessData(AddMemoryBusinessDataReqDto reqDto) {
        String key = reqDto.getBusinessDataObject() + "_" + reqDto.getDataObjectBatchCode();
        JSONObject objectData = new JSONObject();
        for (MemoryBusinessDataDto one : reqDto.getMemoryBusinessDataList()) {
            objectData.put(one.getFieldName(), one.getFieldValue());
        }
        if (reqDto.getIsDataList().equals("TRUE")) {
            Object currentData = CommonFunctionHelper.getBaseInfoFromLocal().getLocalCachePool().get(key);
            if (currentData != null) {
                if (currentData instanceof JSONArray) {
                    JSONArray arrayData = (JSONArray) currentData;
                    arrayData.add(objectData);
                    CommonFunctionHelper.getBaseInfoFromLocal().getLocalCachePool().put(key, arrayData);
                } else {
                    throw new BizException("-1", "想取数据集，但是存的是对象", false);
                }
            } else {
                JSONArray arrayData = new JSONArray();
                arrayData.add(objectData);
                CommonFunctionHelper.getBaseInfoFromLocal().getLocalCachePool().put(key, arrayData);
            }
        } else {
            CommonFunctionHelper.getBaseInfoFromLocal().getLocalCachePool().put(key, objectData);
        }
        return new AddMemoryBusinessDataRespDto();
    }

    /**
     * code:queryMemoryBusinessData
     * name:M3查询内存业务数据详情（特殊方法）
     * desc:undefined
     * gen by moon at 3/15/2024, 11:35:39 PM
     **/
    @Trace(operationName = "M3查询内存业务数据详情（特殊方法）")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public QueryMemoryBusinessDataDetailRespDto queryMemoryBusinessDataDetail(QueryMemoryBusinessDataDetailReqDto reqDto) {
        QueryMemoryBusinessDataDetailRespDto retData = new QueryMemoryBusinessDataDetailRespDto();
        String key = reqDto.getBusinessDataObject() + "_" + reqDto.getDataObjectBatchCode();
        JSONObject currentData = (JSONObject) CommonFunctionHelper.getBaseInfoFromLocal().getLocalCachePool().get(key);
        if (currentData == null) {
            return retData;
        }

        Map<String, Field> fieldIndex = new HashMap<>();
        Field[] fields = QueryMemoryBusinessDataDetailRespDto.class.getDeclaredFields();
        for (Field one : fields) {
            one.setAccessible(true);
            fieldIndex.put(one.getName(), one);
        }


        for (MemoryBusinessResDataDto one : reqDto.getMemoryBusinessResDataList()) {
            Object value = currentData.get(one.getFieldName());
            Field field = fieldIndex.get(one.getMapFieldName());
            if (value != null) {
                try {
                    field.set(retData, String.valueOf(value));
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
        return retData;
    }

    @Trace(operationName = "组装sql")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public String buildSql(ImplementGeneralSubsectionQueryBusinessDataReqDto reqDto) {

        Map<String, String> queryKey = new HashMap<>();

        Map<String, Date> timeQueryKey = new HashMap<>();

        Map<String, String> timeQueryRuleKey = new HashMap<>();
        if (reqDto.getRefCustomField1() != null && reqDto.getRefCustomFieldValue1() != null) {
            queryKey.put(CommonFunctionHelper.humpToUnderline(reqDto.getRefCustomField1()), reqDto.getRefCustomFieldValue1());
        }

        if (reqDto.getRefCustomField2() != null && reqDto.getRefCustomFieldValue2() != null) {
            queryKey.put(CommonFunctionHelper.humpToUnderline(reqDto.getRefCustomField2()), reqDto.getRefCustomFieldValue2());
        }

        if (reqDto.getRefCustomField3() != null && reqDto.getRefCustomFieldValue3() != null) {
            queryKey.put(CommonFunctionHelper.humpToUnderline(reqDto.getRefCustomField3()), reqDto.getRefCustomFieldValue3());
        }

        if (reqDto.getRefCustomField4() != null && reqDto.getRefCustomFieldValue4() != null) {
            queryKey.put(CommonFunctionHelper.humpToUnderline(reqDto.getRefCustomField4()), reqDto.getRefCustomFieldValue4());
        }

        if (reqDto.getRefCustomField5() != null && reqDto.getRefCustomFieldValue5() != null) {
            queryKey.put(CommonFunctionHelper.humpToUnderline(reqDto.getRefCustomField5()), reqDto.getRefCustomFieldValue5());
        }

        if (reqDto.getRefCustomField6() != null && reqDto.getRefCustomFieldValue6() != null) {
            queryKey.put(CommonFunctionHelper.humpToUnderline(reqDto.getRefCustomField6()), reqDto.getRefCustomFieldValue6());
        }

        if (reqDto.getRefCustomField7() != null && reqDto.getRefCustomFieldValue7() != null) {
            queryKey.put(CommonFunctionHelper.humpToUnderline(reqDto.getRefCustomField7()), reqDto.getRefCustomFieldValue7());
        }

        if (reqDto.getRefCustomField8() != null && reqDto.getRefCustomFieldValue8() != null) {
            queryKey.put(CommonFunctionHelper.humpToUnderline(reqDto.getRefCustomField8()), reqDto.getRefCustomFieldValue8());
        }

        if (reqDto.getComTimeFieldName1() != null && reqDto.getComTimeFieldValue1() != null) {
            timeQueryKey.put(CommonFunctionHelper.humpToUnderline(reqDto.getComTimeFieldName1()), reqDto.getComTimeFieldValue1());
            timeQueryRuleKey.put(CommonFunctionHelper.humpToUnderline(reqDto.getComTimeFieldName1()), reqDto.getComTimeFieldRule1());
        }

        if (reqDto.getComTimeFieldName2() != null && reqDto.getComTimeFieldValue2() != null) {
            timeQueryKey.put(CommonFunctionHelper.humpToUnderline(reqDto.getComTimeFieldName2()), reqDto.getComTimeFieldValue2());
            timeQueryRuleKey.put(CommonFunctionHelper.humpToUnderline(reqDto.getComTimeFieldName2()), reqDto.getComTimeFieldRule2());
        }

        StringBuilder where = new StringBuilder();
        if (!queryKey.isEmpty() || !timeQueryKey.isEmpty()) {
            where.append(" WHERE ");
            for (Map.Entry<String, String> entry : queryKey.entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue();
                where.append(key).append(" = ").append("'").append(value).append("'").append(" AND ");
            }

            for (Map.Entry<String, Date> entry : timeQueryKey.entrySet()) {
                String key = entry.getKey();
                String value = DateTimeUtil.dateFormat(entry.getValue());
                String rule = timeQueryRuleKey.get(entry.getKey());
                if (rule.equals("=")) {
                    where.append(key).append(" = ").append("'").append(value).append("'").append(" AND ");
                } else if (rule.equals(">")) {
                    where.append(key).append(" > ").append("'").append(value).append("'").append(" AND ");
                } else if (rule.equals("<")) {
                    where.append(key).append(" < ").append("'").append(value).append("'").append(" AND ");
                } else if (rule.equals(">=")) {
                    where.append(key).append(" >= ").append("'").append(value).append("'").append(" AND ");
                } else if (rule.equals("<=")) {
                    where.append(key).append(" <= ").append("'").append(value).append("'").append(" AND ");
                }
            }

            if (reqDto.getBusinessDataSetPrimaryKeyName() != null
                    && !reqDto.getBusinessDataSetPrimaryKeyName().isEmpty()
                    && reqDto.getLastDataObjectId() != null
                    && !reqDto.getLastDataObjectId().isEmpty()) {
                String priKey = CommonFunctionHelper.humpToUnderline(reqDto.getBusinessDataSetPrimaryKeyName());
                if (priKey.equals("eva_obj_target_cycle_code")) {
                    String priKeySpecStr = CommonFunctionHelper.buildSpecOderBy(priKey);
                    String priKeyValueSpecStr = CommonFunctionHelper.buildSpecOderBy(reqDto.getLastDataObjectId());
                    if (reqDto.getOrderRule() != null && reqDto.getOrderRule().equals("FROM_LARGE_TO_SMALL")) {
                        where.append(priKeySpecStr).append(" < ").append(priKeyValueSpecStr).append(" AND ");
                    } else if (reqDto.getOrderRule() != null && reqDto.getOrderRule().equals("FROM_SMALL_TO_LARGE")) {
                        where.append(priKeySpecStr).append(" > ").append(priKeyValueSpecStr).append(" AND ");
                    }
                } else {
                    if (reqDto.getOrderRule() != null && reqDto.getOrderRule().equals("FROM_LARGE_TO_SMALL")) {
                        where.append(CommonFunctionHelper.humpToUnderline(reqDto.getBusinessDataSetPrimaryKeyName())).append(" < ").append("'").append(reqDto.getLastDataObjectId()).append("'").append(" AND ");
                    } else if (reqDto.getOrderRule() != null && reqDto.getOrderRule().equals("FROM_SMALL_TO_LARGE")) {
                        where.append(CommonFunctionHelper.humpToUnderline(reqDto.getBusinessDataSetPrimaryKeyName())).append(" > ").append("'").append(reqDto.getLastDataObjectId()).append("'").append(" AND ");
                    }

                }

            }
            where.delete(where.length() - 5, where.length());
        }

        StringBuilder orderBy = new StringBuilder();
        if (reqDto.getOrderFieldName() != null) {
            String orderFieldName = CommonFunctionHelper.humpToUnderline(reqDto.getOrderFieldName());
            if (orderFieldName.equals("eva_obj_target_cycle_code")) {
                orderFieldName = CommonFunctionHelper.buildSpecOderBy(orderFieldName);
            }
            orderBy.append(" order by " + orderFieldName);
        }

        if (reqDto.getOrderRule() != null && reqDto.getOrderRule().equals("FROM_LARGE_TO_SMALL")) {
            orderBy.append(" desc ");
        } else if (reqDto.getOrderRule() != null && reqDto.getOrderRule().equals("FROM_SMALL_TO_LARGE")) {
            orderBy.append(" asc ");
        }

        StringBuilder limit = new StringBuilder();
        if (reqDto.getDatasNum() != null) {
            limit.append(" limit " + reqDto.getDatasNum());
        }


        String selectPreFixStr = "SELECT * FROM " + reqDto.getBusinessDataSetTableName() + " ";
        String sql = selectPreFixStr + where.toString() + orderBy.toString() + limit.toString();
        return sql;
    }

    /**
     * code:subsectionQueryBusinessDataSet
     * name:M3执行通用分段查询业务数据对象（特殊方法）
     * desc:undefined
     * gen by moon at 4/18/2024, 6:27:31 PM
     **/
    @Trace(operationName = "M3执行通用分段查询业务数据对象（特殊方法）")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public ImplementGeneralSubsectionQueryBusinessDataRespDto implementGeneralSubsectionQueryBusinessData(ImplementGeneralSubsectionQueryBusinessDataReqDto reqDto) {
        ImplementGeneralSubsectionQueryBusinessDataRespDto retData = new ImplementGeneralSubsectionQueryBusinessDataRespDto();
        String sql = buildSql(reqDto);
        try (Connection connection = dataSource.getConnection();
             PreparedStatement preparedStatement = connection.prepareStatement(sql);
             ResultSet resultSet = preparedStatement.executeQuery()) {

            Map<String, Field> fieldIndex = new HashMap<>();
            Field[] fields = BusinessDataSetDto.class.getDeclaredFields();
            for (Field one : fields) {
                one.setAccessible(true);
                fieldIndex.put(one.getName(), one);
            }

            while (resultSet.next()) {
                BusinessDataSetDto elm = new BusinessDataSetDto();
                Long count = 1L;
                for (OutputBusinessDataDto oneField : reqDto.getOutputBusinessDataList()) {
                    Object value = resultSet.getObject(CommonFunctionHelper.humpToUnderline(oneField.getFieldName()));
                    Field field = fieldIndex.get(oneField.getMapFieldName());
                    if (value != null) {
                        try {
                            field.set(elm, String.valueOf(value));
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        }
                    }
                    count++;
                }
                retData.getBusinessDataSetList().add(elm);
            }
        } catch (Exception e) {
            throw new BizException("M3执行通用分段查询业务数据对象-寻找数据异常:(" + e + ")", false);
        }
        return retData;
    }

    /**
     * code:publicFieldCache
     * name:M3执行空间配置推送内存（APP）
     * desc:undefined
     * gen by moon at 5/19/2024, 2:34:38 PM
     **/
    @Trace(operationName = "M3执行空间配置推送内存（APP）")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public ImplementSpaceConfPushMemoryAppRespDto implementSpaceConfPushMemoryApp(ImplementSpaceConfPushMemoryAppReqDto reqDto) {
        ImplementSpaceConfPushMemoryAppRespDto retData = new ImplementSpaceConfPushMemoryAppRespDto();
        Map<String, Object> confPool = CommonFunctionHelper.getBizConfigInfo();
        if (confPool.containsKey(reqDto.getSpaceId())) {
            Map<String, Object> spaceConfig = (Map<String, Object>) confPool.get(reqDto.getSpaceId());
            spaceConfig.put("fileDisplayRootPath", reqDto.getFileDisplayRootPath());
        } else {
            Map<String, Object> spaceConfig = new HashMap<>();
            spaceConfig.put("fileDisplayRootPath", reqDto.getFileDisplayRootPath());
            confPool.put(reqDto.getSpaceId(), spaceConfig);
        }
        return retData;
    }

    /**
     * code:receptionService
     * name:M3-获取当前空间文档展示根路径
     * desc:undefined
     * gen by moon at 5/20/2024, 12:42:57 AM
     **/
    @Trace(operationName = "M3-获取当前空间文档展示根路径")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public ImplementElevenReceivingFieldRespDto implementElevenReceivingField(ImplementElevenReceivingFieldReqDto reqDto) {
        return BeanUtil.toBean(reqDto, ImplementElevenReceivingFieldRespDto.class);
    }

    //手工接入方法
}
